package com.tang.framework.delay.support;

import org.jetbrains.annotations.NotNull;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * @Author tang jun liang
 * @Date 2023/4/16 15:44
 */
@Component
@ConditionalOnProperty(prefix = "cool-tea", name = "delay", havingValue = "true")
public class DelayBeanPostProcess implements BeanPostProcessor, ApplicationContextAware {

    private ApplicationContext applicationContext;

    private DelayContext delayContext = null;


    @Override
    public Object postProcessAfterInitialization(@NotNull Object bean, @NotNull String beanName) throws BeansException {
        if ((bean instanceof RedissonClient)){
            return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
        }
        if (Objects.isNull(delayContext)) {
            delayContext = new DelayContext(applicationContext.getBean(RedissonClient.class));
            DelayHolder.setContext(delayContext);
        }
        delayContext.processBean(bean);
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    public void delayRun(ApplicationReadyEvent applicationReadyEvent){
        this.delayContext.run(applicationReadyEvent);
    }
}
